package com.lance.answer.gui.answer.gk.answer.lms.batch.task;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.lance.answer.dto.CompleteInfo;
import com.lance.answer.gui.answer.Util;
import com.lance.answer.gui.answer.gk.answer.lms.Courseware;
import com.lance.answer.gui.answer.gk.answer.lms.LmsVideoInfo;
import com.lance.answer.gui.answer.gk.answer.lms.YiWangYiVideoReturnInfo;
import com.lance.answer.gui.answer.gk.answer.lms.batch.dto.LmsWatchDTO;
import com.lance.answer.gui.answer.gk.answer.lms.util.LmsUtil;
import com.lance.answer.util.HttpUtil;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.WebDriverWait;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.time.Duration;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.TimeUnit;

@Slf4j
public class BatchLmsSaveVideoTask extends Thread {


    private final String driverPath;
    private final LinkedBlockingDeque<LmsWatchDTO> watchDTOS;

    public BatchLmsSaveVideoTask(String driverPath, LinkedBlockingDeque<LmsWatchDTO> watchDTOS) {
        this.driverPath = driverPath;
        this.watchDTOS = watchDTOS;
    }

    @SneakyThrows
    @Override
    public void run() {

        while (watchDTOS.size() > 0) {
            LmsWatchDTO lmsWatchDTO = watchDTOS.take();
            String userName = lmsWatchDTO.getUsername();
            String password = lmsWatchDTO.getPassword();
            log.info("任务：{} 剩余 {} 行 用户名：{} 密码：{} 课程：{}",
                    Thread.currentThread().getName(), watchDTOS.size(), userName, password,lmsWatchDTO.getCourseName());
            System.err.println("执行任务11111");
            run(driverPath, lmsWatchDTO);
        }

        if (watchDTOS.size() == 0) {
            log.info("课程所有用户均已执行完毕，系统将在20min后结束");
            TimeUnit.MINUTES.sleep(20);
            return;
        }
    }


    public static void run(String driverPath, LmsWatchDTO lmsWatchDTO) throws Exception {

        String userName = lmsWatchDTO.getUsername();
        String pwd = lmsWatchDTO.getPassword();
        String courseName = lmsWatchDTO.getCourseName();
        long courseId = lmsWatchDTO.getCourseId();

        try {

            String completeInfoFilePath = "libs//lmsAnswerInfo//" + courseName + "//";
            completeInfoFilePath = completeInfoFilePath + userName + "-study.txt";


            File completeInfoFile = new File(completeInfoFilePath);

            if (completeInfoFile.exists()) {
                InputStream completeInfoStream = new FileInputStream(completeInfoFile);
                String completeInfoStr = IOUtils.toString(completeInfoStream, "UTF-8");
                List<CompleteInfo> completeInfoList = JSONObject.parseArray(completeInfoStr, CompleteInfo.class);
                if (completeInfoList != null) {
                    if (courseName.equals("形势与政策") && completeInfoList.size() >= 5) {
                        return;
                    }
                    if (courseName.equals("毛泽东思想和中国特色社会主义理论体系概论") && completeInfoList.size() >= 8) {
                        return;
                    }
                    if (courseName.equals("中国近现代史纲要") && completeInfoList.size() >= 7) {
                        return;
                    }
                    if (courseName.equals("思想道德与法治") && completeInfoList.size() >= 8) {
                        return;
                    }
                    if (courseName.equals("习近平新时代中国特色社会主义思想") && completeInfoList.size() >= 15) {
                        return;
                    }
                    if (courseName.equals("马克思主义基本原理") && completeInfoList.size() >= 8) {
                        return;
                    }
//                    if (courseName.equals("国家开放大学学习指南") && completeInfoList.size() >= 5) {
//                        return;
//                    }
//                    if (courseName.equals("计算机应用基础") && completeInfoList.size() >= 3) {
//                        return;
//                    }
                }

            }
        } catch (Exception e) {

        }


        ChromeDriver driver = Util.getDriver(driverPath);

        try {
            String url = "https://menhu.pt.ouchn.cn/site/ouchnPc/index";
            driver.get(url);
            Thread.sleep(3000);


            LmsUtil.login(driver, userName, pwd);

            Thread.sleep(10000);


            try {


                studyVideo(driver, courseId);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } catch (Exception e1) {

        } finally {
            try {
                driver.close();
                driver.quit();
            } catch (Exception e2) {

            }

        }


    }

    public static void studyVideo(WebDriver driver, Long courseId) throws InterruptedException {
        driver.get("https://lms.ouchn.cn/course/" + courseId + "/ng#/courseware");

        Thread.sleep(5000);
        int page = 1;
        int pageSize = 20;
        boolean hasNextPage = true;
        List<LmsVideoInfo> lmsVideoInfos = Lists.newArrayList();
        while (hasNextPage) {
            Courseware courseware = null;
            try {
                courseware = getUserCourseInfo(driver, courseId, page, pageSize);
            } catch (Exception e) {
                e.printStackTrace();
            }

            System.err.println("???11:" + courseware.getActivities().size());
            for (Courseware.ActivitiesDTO activitiesDTO : courseware.getActivities()) {

              //  System.err.println("activitiesDTO:" + JSON.toJSONString(activitiesDTO));
                if (null == activitiesDTO) {
                    continue;
                }
                if (null == activitiesDTO.getUploads()) {
                    continue;
                }


                List<Courseware.ActivitiesDTO.PrerequisitesDTO> prerequisites = activitiesDTO.getPrerequisites();
                if (prerequisites != null && prerequisites.size() > 0) {
                    // 06-26注释掉的。。。
//                    if (prerequisites.get(0).getCompletionCriterion().getHasCompleted()) {
//                        /**
//                         *   "has_completed": false 这个可以判断  视频作业是否完成，完成就不加入到list集合去了
//                         *   这里还需进一步的验证！！！！！！！！
//                         */
//                        continue;
//                    }
                    // 06-26注释掉的。。。
                }

                LmsVideoInfo lmsVideoInfo = new LmsVideoInfo();
                lmsVideoInfos.add(lmsVideoInfo);
                lmsVideoInfo.setVideoId(activitiesDTO.getId());

                for (Courseware.ActivitiesDTO.UploadsDTO uploadsDTO : activitiesDTO.getUploads()) {
                    if (null == uploadsDTO.getVideos() || uploadsDTO.getVideos().size() < 1) {
                        continue;
                    }
                    //     System.err.println(">>>>>>>>>>>"+uploadsDTO.getVideos().size());
                    lmsVideoInfo.setVideoLength(uploadsDTO.getVideos().get(0).getDuration().intValue());
                }
            }
            if (page >= courseware.getPages()) {
                hasNextPage = false;
            } else {
                //  hasNextPage = false;
                page++;
            }
            Thread.sleep(5000);
        }

        System.err.println("videosDTOSSize:" + lmsVideoInfos.size());

        Collections.sort(lmsVideoInfos);

        for (LmsVideoInfo videoInfo : lmsVideoInfos) {

            System.err.println("id::::" + videoInfo.getVideoId());

            try {
                saveVideoInfo(courseId, videoInfo.getVideoId(), videoInfo.getVideoLength(), Util.getCookie(driver.manage().getCookies()));
            } catch (Exception e) {
                e.printStackTrace();
            }
            Thread.sleep(5000);
        }

        System.err.println("end...............");

        //    Thread.sleep(2000000);
    }

    public static Courseware getUserCourseInfo(WebDriver driver, Long courseId, int page, int pageSize) throws Exception {


        String cookie = Util.getCookie(driver.manage().getCookies());

//        int page = 1;
//        int pageSize=20;
        String getUrl = "https://lms.ouchn.cn/api/course/" + courseId + "/coursewares?conditions=%7B%22category%22:null,%22itemsSortBy%22:%7B%22predicate%22:%22chapter%22,%22reverse%22:false%7D,%22ignore_activity_types%22:%5B%22lesson%22%5D%7D" +
                "&page=" + page + "&page_size=" + pageSize;

        Map<String, String> heads = Maps.newHashMap();
        heads.put("referer", "https://lms.ouchn.cn/course/" + courseId + "/ng");
        heads.put(":method", "GET");
        heads.put(":authority", "lms.ouchn.cn");
        heads.put("cookie", cookie);
        //     heads.put(":path", "/api/course/" + courseId + "/activity-reads-for-user");
        heads.put("accept", "application/json, text/plain, */*");

        String result = HttpUtil.getLmsOuchn(getUrl, cookie, heads);
        //   System.err.println("result:::" + result);
        return JSON.parseObject(result, Courseware.class);
    }


    public static void saveVideoInfo(long courseId, long videoId, int videoLength, String cookie) throws Exception {

        String postUrl = "https://lms.ouchn.cn/api/course/activities-read/" + videoId;

        Map<String, String> heads = Maps.newHashMap();
        heads.put("referer", "https://lms.ouchn.cn/course/" + courseId + "/learning-activity/full-screen");
        heads.put(":method", "POST");
        heads.put(":authority", "lms.ouchn.cn");
        heads.put("origin", "https://lms.ouchn.cn");
        heads.put("cookie", cookie);
        heads.put(":path", "/api/course/activities-read/" + videoId);

        // Map<String,Object> data   = Maps.newHashMap();
        JSONObject saveJson = new JSONObject();
        // 课程ID，固定的
        //   int videoLength = 449;

        // int defaultStep = 60;
        //  int defaultStep = 360 ;
        //  int defaultStep = 360;
        int defaultStep = 360;
        int end = 0;
        while (end < videoLength) {
            saveJson.clear();
            saveJson.put("start", end);
            saveJson.put("end", Math.min((end + defaultStep), videoLength));
            String result = HttpUtil.postJson(postUrl, saveJson, cookie, heads);
            System.err.println(result);
            YiWangYiVideoReturnInfo returnInfo = JSON.parseObject(result, YiWangYiVideoReturnInfo.class);
            /**
             * 4-20 "completeness":"full" 已经为full状态时候，是否可以提前终止while循环？
             * FIXME 需要检查核验
             */
            if ("full".equals(returnInfo.getCompleteness())) {
                end = videoLength;
                break;
            }
            end = returnInfo.getData().getEnd();
            Thread.sleep(5000);
        }
        saveJson.clear();
        saveJson.put("start", end - 20);
        saveJson.put("end", end);
        System.err.println(HttpUtil.postJson(postUrl, saveJson, cookie, heads));
    }


    public static List<WebElement> findElementsByCssSelector(WebDriver driver, String cssSelector, long seconds) {
        return (new WebDriverWait(driver, Duration.ofSeconds(seconds)).until((ExpectedCondition<List<WebElement>>)
                d -> {
                    assert d != null;
                    return d.findElements(By.cssSelector(cssSelector));
                }));
    }

    public static WebElement findElementByCssSelector(WebDriver driver, String cssSelector, long seconds) {
        return (new WebDriverWait(driver, Duration.ofSeconds(seconds)).until((ExpectedCondition<WebElement>)
                d -> {
                    assert d != null;
                    return d.findElement(By.cssSelector(cssSelector));
                }));
    }


}
